import os
from configparser import ConfigParser
from typing import Dict, Any


class BaseConfigParser(ConfigParser):
    def to_dict(self) -> Dict:
        return {
            section: dict(self[section])
            for section in self.sections()
        }


def load_conf(path:str) -> Dict:
    _cfg = BaseConfigParser()
    result = {}
    if not os.path.isfile(path):
        raise ValueError(f"配置文件 {path} 不存在")
    try:
        _cfg.read(path,encoding='UTF-8')
        result = _cfg.to_dict()
    except Exception  as e:
        raise ValueError(f"解析配置文件{path}失败:{str(e)}")
    
    return result




# 使用案例
if __name__ == "__main__":
    cfg_name = "utils/tmp.ini"
    cfg_data = """
[sys]
base_url = https://www.jd.com

[smtp]
host = smtp.163.com
port = 465
user = example@163.com
passwd = password

"""
    fd = os.open(cfg_name,os.O_RDWR | os.O_CREAT)
    os.write(fd,bytes(cfg_data,encoding='UTF-8'))
    os.close(fd)

    conf = load_conf(cfg_name)
    print(conf)
    print(conf['sys']['base_url'])